package com.cennavi.minemapdemo.activity.ue;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.RadioGroup;

import com.cennavi.minemapdemo.R;
import com.cennavi.minemapdemo.activity.BaseActivty;
import com.cennavi.minemapdemo.util.Config;
import com.cennavi.minemapdemo.util.DensityUtil;
import com.minedata.minemap.MinemapAccountManager;
import com.minedata.minemap.camera.CameraPosition;
import com.minedata.minemap.camera.CameraUpdateFactory;
import com.minedata.minemap.geometry.LatLng;
import com.minedata.minemap.map.MapView;
import com.minedata.minemap.map.MineMap;
import com.minedata.minemap.overlay.MarkerLayer;
import com.minedata.minemap.overlay.MarkerLayerOptions;
import com.minedata.minemap.overlay.NavigationLayer;
import com.minedata.minemap.overlay.NavigationOptions;
import com.minedata.minemap.overlay.PolyLineLayer;
import com.minedata.minemap.overlay.PolyLineLayerOptions;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import static com.minedata.minemap.overlay.NavigationOptions.NAVIGATION_CAP_ROUND;
import static com.minedata.minemap.overlay.NavigationOptions.NAVIGATION_JOIN_ROUND;

public class LayerSwitchActivity extends BaseActivty {
    public static final String base = Config.BASE_URL + Config.MAP_ID;//标准地图
    public static final String bus = Config.BASE_URL + "16871";//公交地图

    private MapView mMapView;
    private static MineMap mMineMap;
    private Context mContext;
    private NavigationLayer navigationLayer;
    private PolyLineLayer polyLineLayer;
    private PolyLineLayer dashPolyLineLayer;
    private MarkerLayer markerLayer;
    private int chooseMap = 0;
    private String iconName = "walk";
    private Bitmap icon = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        MinemapAccountManager.getInstance(this, Config.MAP_TOK, Config.OFFLINE_TOK, Config.MAP_ID);
        setContentView(R.layout.activity_ue_layer_switch);
        initView();
        initMap();
    }

    private void initMap() {
        mMapView.setApiBaseUrl(Config.API_BASE_URL);
        mMapView.setApiUrl(Config.API_URL);
        mMapView.setSpriteImageUrl(Config.SPRITE_GLYPHS_URL);
        mMapView.addMapRenderCallback(new MapView.OnMapReadyListener() {
            @SuppressLint("RtlHardcoded")
            @Override
            public void onMapReady(MineMap oMineMap) {
                mMineMap = oMineMap;
                mMineMap.getUiSettings().setRotateGesturesEnabled(true);// 是否可以旋转地图
                mMineMap.getUiSettings().setTiltGesturesEnabled(true);
                mMineMap.getUiSettings().setLogoEnabled(true);
                mMineMap.setRepaint(true);
                mMineMap.setStyleUrl(bus, new MineMap.OnStyleLoadedListener() {
                    @Override
                    public void onStyleLoaded(String s) {
                        chooseMap = 1;
                        mMineMap.setTrafficShow(true); //是否展示交通路况信息
                        mMineMap.setTrafficRote(60);//路况刷新时间
                    }
                });
                //设置指南针是否显示，默认是显示
                mMineMap.getUiSettings().setCompassEnabled(true);
                mMineMap.getUiSettings().setCompassGravity(Gravity.LEFT);
//                mineMap.getUiSettings().setCompassImage(getResources().getDrawable(R.mipmap.icon_compass));
                mMineMap.getUiSettings().setCompassMargins(DensityUtil.dip2px(mContext, 11), DensityUtil.dip2px(mContext, 80),
                        0, 0);
                mMineMap.setCameraPosition(
                        new CameraPosition.Builder().target(new LatLng(41.81092, 123.43445))
                                .zoom(15)
                                .tilt(0)//设定倾斜角度
                                .bearing(0) //摄像机指向的方向,从北部顺时针方向设置
                                .build());
                mMineMap.setMaxZoomPreference(17);//设置最高展示级别，最高为17级别
                mMineMap.setMinZoomPreference(3);//设置最低的展示级别
            }
        });
    }

    private void initView() {
        mMapView = findViewById(R.id.mapview);
        RadioGroup radioGroup = findViewById(R.id.radio_group);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {

                switch (i) {
                    case R.id.layer_bus:

                        if (chooseMap == 0) {
                            mMineMap.setStyleUrl(bus, new MineMap.OnStyleLoadedListener() {
                                @Override
                                public void onStyleLoaded(String s) {
                                    chooseMap = 1;
                                    mMineMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(41.81092, 123.43445)));
                                    mMineMap.setZoom(15);
                                }
                            });
                        }

                        break;
                    case R.id.layer_drive:
                        if (chooseMap == 1) {
                            mMineMap.setStyleUrl(base, new MineMap.OnStyleLoadedListener() {
                                @Override
                                public void onStyleLoaded(String s) {
                                    chooseMap = 0;
                                    mMineMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(41.81092, 123.43445)));
                                    mMineMap.setZoom(11);
                                    addDrive();
                                }
                            });
                        } else {
                            mMineMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(41.81092, 123.43445)));
                            mMineMap.setZoom(11);
                            addDrive();
                        }
                        break;
                    case R.id.layer_walk:
                        if (chooseMap == 1) {
                            mMineMap.setStyleUrl(base, new MineMap.OnStyleLoadedListener() {
                                @Override
                                public void onStyleLoaded(String s) {
                                    addImageToMap();
                                    chooseMap = 0;
                                    mMineMap.setZoom(11);
                                    mMineMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(41.85817, 123.58460)));
                                    addWalk();
                                }
                            });
                        } else {
                            addImageToMap();
                            mMineMap.setZoom(11);
                            mMineMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(41.85817, 123.58460)));
                            addWalk();
                        }
                        break;
                }
            }
        });
    }

    //加载图片资源
    private void addImageToMap() {
        icon = BitmapFactory.decodeResource(getResources(), R.drawable.walk);

        if (mMineMap.getImage(iconName) == null) {
            mMineMap.addImage(iconName, icon);
        }
    }

    //添加驾车图层
    public void addDrive() {
        if (navigationLayer != null) {
            mMineMap.removeLayer(navigationLayer);
            navigationLayer = null;
        }

        if (polyLineLayer != null) {
            mMineMap.removeLayer(polyLineLayer);
            polyLineLayer = null;
        }

        if (dashPolyLineLayer != null) {
            mMineMap.removeLayer(dashPolyLineLayer);
            dashPolyLineLayer = null;
        }

        if (markerLayer != null) {
            mMineMap.removeLayer(markerLayer);
            markerLayer = null;
        }

        NavigationOptions options = new NavigationOptions("navigationlayer");
        options.setAlpha(1.0f);
        options.setWidth(8.0f);
        options.setAnimationDuration(1000);
        options.setAnimationMode(NavigationOptions.NAVIGATION_ANIMATION_MODE_SINGLE);
        options.setCapType(NAVIGATION_CAP_ROUND);
        options.setJoinType(NAVIGATION_JOIN_ROUND);
        options.setBottomColorEnabled(true);
        options.setBottomColor("#C0C0C0");
        options.setProgressMode(NavigationOptions.NAVIGATION_PROGRESS_MODE_LTE);
        options.setProgress(0);
        options.addAll(getDrivePointsData());
        navigationLayer = mMineMap.addLayer(options);
    }

    //添加步行图层
    public void addWalk() {
        if (navigationLayer != null) {
            mMineMap.removeLayer(navigationLayer);
            navigationLayer = null;
        }

        if (polyLineLayer != null) {
            mMineMap.removeLayer(polyLineLayer);
            polyLineLayer = null;
        }

        if (dashPolyLineLayer != null) {
            mMineMap.removeLayer(dashPolyLineLayer);
            dashPolyLineLayer = null;
        }

        if (markerLayer != null) {
            mMineMap.removeLayer(markerLayer);
            markerLayer = null;
        }

        List<LatLng> points = getWalkPointsData();

        PolyLineLayerOptions.PolylineItem item1 = new PolyLineLayerOptions.PolylineItem(points.subList(0, points.size() - 1), "#9b29e7");

        PolyLineLayerOptions options1 = new PolyLineLayerOptions("polylineLayer");
        options1.add(item1);
        options1.lineWidth(8.0f);
        options1.lineCapType(PolyLineLayerOptions.LINE_CAP_ROUND);
        options1.lineJoinType(PolyLineLayerOptions.LINE_JOIN_ROUND);
        polyLineLayer = mMineMap.addLayer(options1);


        PolyLineLayerOptions.PolylineItem item2 = new PolyLineLayerOptions.PolylineItem(points.subList(points.size() - 2, points.size()), "#9b29e7");

        PolyLineLayerOptions options2 = new PolyLineLayerOptions("dashpolylineLayer");
        options2.add(item2);
        options2.lineWidth(8.0f);
        options2.dashArray(new Float[]{1.5f, 1.5f});
        options2.lineCapType(PolyLineLayerOptions.LINE_CAP_ROUND);
        options2.lineJoinType(PolyLineLayerOptions.LINE_JOIN_ROUND);
        dashPolyLineLayer = mMineMap.addLayer(options2);

        List<MarkerLayerOptions.MarkerItem> symbolItems = new ArrayList<>();
        symbolItems.add(new MarkerLayerOptions.MarkerItem()
                .icon(iconName).position(points.get(0)));
        symbolItems.add(new MarkerLayerOptions.MarkerItem()
                .icon(iconName).position(points.get(points.size() - 2)));

        MarkerLayerOptions options = new MarkerLayerOptions("iconmarkerlayer")
                .iconPitchAlignment(MarkerLayerOptions.PITCH_ALIGNMENT_MAP)
                .iconRotationAlignment(MarkerLayerOptions.ROTATION_ALIGNMENT_VIEWPORT);
        options.addAll(symbolItems);
        markerLayer = mMineMap.addLayer(options);
    }

    //获取驾车路线数据
    public List<NavigationOptions.NavigationItem> getDrivePointsData() {
        List<NavigationOptions.NavigationItem> items = new ArrayList<>();

        try {
            InputStream instream = getAssets().open("drive_data.csv");
            List<LatLng> points = new ArrayList<>();

            if (instream != null) {
                InputStreamReader inputreader = new InputStreamReader(instream);
                BufferedReader buffreader = new BufferedReader(inputreader);
                String line;

                while ((line = buffreader.readLine()) != null) {
                    String everyLine = line;
                    String[] strarray = everyLine.split(",");

                    double longitude = (double) Integer.parseInt(strarray[0]) / 100000;
                    double latitude = (double) Integer.parseInt(strarray[1]) / 100000;
                    points.add(new LatLng(latitude, longitude));
                }
                instream.close();
                buffreader.close();
            }

            NavigationOptions.NavigationItem item = new NavigationOptions.NavigationItem(points, "#3CB371");
            items.add(item);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return items;
    }

    //获取步行路线数据
    public List<LatLng> getWalkPointsData() {
        List<LatLng> points = new ArrayList<>();
        try {
            InputStream instream = getAssets().open("walk_data.csv");

            if (instream != null) {
                InputStreamReader inputreader = new InputStreamReader(instream);
                BufferedReader buffreader = new BufferedReader(inputreader);
                String line;

                while ((line = buffreader.readLine()) != null) {
                    String everyLine = line;
                    String[] strarray = everyLine.split(",");

                    double longitude = (double) Integer.parseInt(strarray[0]) / 100000;
                    double latitude = (double) Integer.parseInt(strarray[1]) / 100000;
                    points.add(new LatLng(latitude, longitude));
                }
                instream.close();
                buffreader.close();
            }


        } catch (IOException e) {
            e.printStackTrace();
        }

        return points;
    }

    @Override
    protected void onStart() {
        if (mMapView != null) {
            mMapView.onStart();
        }
        super.onStart();
    }

    @Override
    protected void onResume() {
        if (mMapView != null)
            mMapView.onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        if (mMapView != null)
            mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onStop() {
        if (mMapView != null)
            mMapView.onStop();
        super.onStop();
    }

    @Override
    public void onDestroy() {
        if (mMapView != null)
            mMapView.onDestroy();
        super.onDestroy();
    }
}
